package reduce.fz.com.reduce.activity;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;

import java.util.HashMap;
import java.util.List;

import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.abstracts.AbResponseListener;
import reduce.fz.com.reduce.adapter.BaseListAdapter;
import reduce.fz.com.reduce.adapter.BaseRecycleViewHolder;
import reduce.fz.com.reduce.bean.ServiceException;
import reduce.fz.com.reduce.bean.Society;
import reduce.fz.com.reduce.bean.User;
import reduce.fz.com.reduce.bean.Video;
import reduce.fz.com.reduce.bean.VideoCard;
import reduce.fz.com.reduce.bean.page.Pagination;
import reduce.fz.com.reduce.bean.result.Result;
import reduce.fz.com.reduce.custom.LoadingDialog;
import reduce.fz.com.reduce.custom.NetworkImageView;
import reduce.fz.com.reduce.custom.view.RoundNetworkImageView;
import reduce.fz.com.reduce.service.SocietyService;
import reduce.fz.com.reduce.util.DateUtil;
import reduce.fz.com.reduce.util.HttpUtils;
import reduce.fz.com.reduce.util.QuPaiOper;
import reduce.fz.com.reduce.util.ServiceBuilder;
import reduce.fz.com.reduce.util.ToastUtil;

public class SocietyDetailActivity extends BaseToolBarActivity implements View.OnClickListener {

    //社团封面
    private NetworkImageView mThum;
    //社团名称
    private TextView mSocietyName;
    //社团描述
    private TextView mSocietyDesc;
    //社团公告点击按钮
    private LinearLayout mLlNotifys;
    //社团作品按钮
    private LinearLayout mLlWorks;
    //社团成员按钮
    private LinearLayout mLlMembers;

    private TextView mToolBtn;

    private LinearLayout mNoInfo;


    private Video video = null;

    //贡献度全部
    private TextView mTvContributionAll;

    private LinearLayout mContributionSection;
    private LinearLayout mDynamicSection;


    private LinearLayout mLlQuit;

    private LinearLayout mLLJoinBar;

    private Boolean isJoin;

    private BaseListAdapter<SocietyDynamicViewHolder, VideoCard> adapter;

    //前几名用户
    private List<User> users;
    //前几条动态
    private List<VideoCard> videoCards;
    //top three贡献度排行
    private LinearLayout mTopThree;
    //社团id
    private Long sid;
    private TextView mJoin;
    //社团
    private Society society;
    private TextView mDynamicALl;
    private RecyclerView mDynamicList;
    private SocietyService societyService = ServiceBuilder.builderSocietyService(null);


    public interface SocietyDynamicItemListener {

        public void dynamicClick(VideoCard video);
    }

    public static class SocietyDynamicViewHolder extends BaseRecycleViewHolder<VideoCard> {

        //视频封面
        private NetworkImageView videoThum;
        //用户昵称
        private TextView mNickname;
        //视频描述
        private TextView mVideoDesc;
        //发布时间
        private TextView mPubtime;
        //监听
        private SocietyDynamicItemListener listener;

        public void initWidget(View itemView) {
            videoThum = (NetworkImageView) itemView.findViewById(R.id.video_thum);
            mNickname = (TextView) itemView.findViewById(R.id.tv_user_nickname);
            mVideoDesc = (TextView) itemView.findViewById(R.id.tv_video_desc);
            mPubtime = (TextView) itemView.findViewById(R.id.tv_pub_time);

        }

        public SocietyDynamicViewHolder(View itemView, SocietyDynamicItemListener listener) {
            this(itemView);
            this.listener = listener;
        }

        public SocietyDynamicViewHolder(View itemView) {
            super(itemView);
            initWidget(itemView);
        }

        @Override
        public void renderView(VideoCard data, int position) {
            videoThum.setImageUrl(data.video.thumUrl, HttpUtils.getImageLoader());
            mNickname.setText(data.user.nickname);
            mVideoDesc.setText(data.description);
            mPubtime.setText(DateUtil.getInterval(data.pubtime));
        }
    }


    /**
     * 加载社团详情
     */
    public void loadSocoetyDetail() {
        final LoadingDialog dialog = new LoadingDialog(this);
        dialog.show();
        societyService.getSociety(sid, new AbResponseListener<Society>(new TypeReference<Result<Society>>() {
        }) {
            @Override
            public void error(ServiceException e) {
                dialog.dismiss();
            }

            @Override
            public void responseInfo(Result<Society> data) {
                dialog.dismiss();
                society = data.getData();
                isJoin = society.attach.isJoin;
                renderWidget();
                dealJoin(isJoin);
            }
        });
    }

    /**
     * 是否加入的控制
     *
     * @param isJoin
     */
    public void dealJoin(Boolean isJoin) {
        if (isJoin) {
            mJoin.setSelected(true);
            mJoin.setText("已加入");
            mLLJoinBar.setVisibility(View.VISIBLE);
            mLlQuit.setVisibility(View.VISIBLE);
        } else {
            mJoin.setSelected(false);
            mLLJoinBar.setVisibility(View.GONE);
            mLlQuit.setVisibility(View.GONE);

        }
    }


    /**
     * 添加前三名top
     *
     * @param user
     * @param rank
     */
    public void renderTopMember(User user, int rank) {

        View view = getLayoutInflater().inflate(R.layout.view_contribution_member_atavar, null);
        RoundNetworkImageView matavar = (RoundNetworkImageView) view.findViewById(R.id.iv_user_avatar);
        ImageView mrank = (ImageView) view.findViewById(R.id.iv_rank);
        matavar.setImageUrl(user.avatar, HttpUtils.getAvatarImageLoader());
        switch (rank) {
            case 1:
                mrank.setImageResource(R.drawable.contribution_no1);
                break;
            case 2:
                mrank.setImageResource(R.drawable.contribution_no2);
                break;
            case 3:
                mrank.setImageResource(R.drawable.contribution_no3);
                break;
            default:
                break;
        }
        int height = getResources().getDimensionPixelSize(R.dimen.dimen_180);
        int margin = getResources().getDimensionPixelSize(R.dimen.dimen_60);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(height, height);
        lp.setMargins(margin, 0, 0, 0);
        view.setLayoutParams(lp);
        mTopThree.addView(view);
    }

    /**
     * 前5条动态render
     */
    public void renderTopFiveDynamic() {
        if (videoCards == null || videoCards.isEmpty()) return;
        adapter.initDatas(videoCards);
        int height = getResources().getDimensionPixelSize(R.dimen.dimen_300) * videoCards.size();
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
        mDynamicList.setLayoutParams(lp);
    }


    //获取贡献度最高的3个用户
    public void getTopThree() {
        societyService.getTopMember(sid, 3, new AbResponseListener<List<User>>(new TypeReference<Result<List<User>>>() {
        }) {
            @Override
            public void error(ServiceException e) {

            }

            @Override
            public void responseInfo(Result<List<User>> data) {
                users = data.getData();
                if (users != null && users.size() > 0) {
                    mNoInfo.setVisibility(View.GONE);
                    mContributionSection.setVisibility(View.VISIBLE);
                    for (int i = 0; i < users.size(); i++) {
                        renderTopMember(users.get(i), i + 1);
                    }
                } else {
                    mNoInfo.setVisibility(View.VISIBLE);
                    mContributionSection.setVisibility(View.GONE);
                }
            }
        });
    }

    //获取最近5条动态
    public void getTopFiveDynamic() {
        societyService.getTopDynamic(sid, 5, new AbResponseListener<List<VideoCard>>(new TypeReference<Result<List<VideoCard>>>() {
        }) {
            @Override
            public void error(ServiceException e) {

            }

            @Override
            public void responseInfo(Result<List<VideoCard>> data) {
                videoCards = data.getData();
                if (videoCards == null || videoCards.isEmpty()) {
                    mDynamicSection.setVisibility(View.GONE);

                } else {
                    mDynamicSection.setVisibility(View.VISIBLE);
                    renderTopFiveDynamic();
                }

            }
        });
    }

    /**
     * 填充数据
     */
    public void renderWidget() {
        mThum.setImageUrl(society.thumurl, HttpUtils.getImageLoader());
        mSocietyName.setText(society.sname);
        mSocietyDesc.setText(society.description);
    }

    /**
     * 获取参数
     */
    public void getParams() {
        sid = getIntent().getLongExtra("sid", 0);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_society_detail);
        setToolbarTitle("我的社团");

        initWidget();
        getParams();
        loadSocoetyDetail();
        getTopThree();
        getTopFiveDynamic();
    }

    public void initRecycleView() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        // 设置ItemAnimator
        mDynamicList.setItemAnimator(new DefaultItemAnimator());
        // 设置固定大小
        mDynamicList.setHasFixedSize(true);
        mDynamicList.setLayoutManager(mLayoutManager);
    }

    @Override
    public void initWidget() {
        mNoInfo=(LinearLayout)findViewById(R.id.ll_no_info);
        mTopThree = (LinearLayout) findViewById(R.id.ll_top_three);
        mDynamicList = (RecyclerView) findViewById(R.id.rv_dynamic_list);
        initRecycleView();
        adapter = new BaseListAdapter<SocietyDynamicViewHolder, VideoCard>(this) {
            @Override
            public SocietyDynamicViewHolder createViewHolder(ViewGroup parent) {
                View view = getLayoutInflater().inflate(R.layout.view_society_dynamic_item, parent, false);
                return new SocietyDynamicViewHolder(view, new SocietyDynamicItemListener() {
                    @Override
                    public void dynamicClick(VideoCard video) {
                        forwardVideoCard(video);
                    }
                });
            }
            @Override
            public SocietyDynamicViewHolder createHeaderHolder(ViewGroup parent) {
                return null;
            }

            @Override
            public SocietyDynamicViewHolder createFooterStatusViewHolder(View footerView) {
                return new SocietyDynamicViewHolder(footerView);
            }
        };

        mDynamicList.setAdapter(adapter);
        mContributionSection = (LinearLayout) findViewById(R.id.ll_contrbution_section);
        mDynamicSection = (LinearLayout) findViewById(R.id.ll_dynamic_section);
        mLlQuit = (LinearLayout) findViewById(R.id.ll_quit);
        mLLJoinBar = (LinearLayout) findViewById(R.id.ll_join_bar);
        mJoin = (TextView) findViewById(R.id.tv_join);
        mThum = (NetworkImageView) findViewById(R.id.society_thum);
        mSocietyName = (TextView) findViewById(R.id.tv_name);
        mSocietyDesc = (TextView) findViewById(R.id.tv_desc);
        mLlNotifys = (LinearLayout) findViewById(R.id.ll_notifys);
        mLlWorks = (LinearLayout) findViewById(R.id.ll_works);
        mLlMembers = (LinearLayout) findViewById(R.id.ll_members);
        mTvContributionAll = (TextView) findViewById(R.id.tv_contrubution_rank_all);
        mDynamicALl = (TextView) findViewById(R.id.tv_dynamic_all);

        mLlNotifys.setOnClickListener(this);
        mLlWorks.setOnClickListener(this);
        mLlMembers.setOnClickListener(this);
        mTvContributionAll.setOnClickListener(this);
        mDynamicALl.setOnClickListener(this);
        mJoin.setOnClickListener(this);
        mLlQuit.setOnClickListener(this);


    }

    /**
     * 跳转到更多动态页面
     */
    public void forwardMoreDynamic() {
        Intent intent = new Intent(this, SocietyDynamicActivity.class);
        intent.putExtra("sid", society.sid);
        startActivity(intent);
    }

    /**
     * 跳转到红人榜页面
     */
    public void forwardMemberRank() {
        Intent intent = new Intent(this, SocietyMemberRankActiviy.class);
        intent.putExtra("sid", sid);
        startActivity(intent);
    }

    /**
     * 跳转到社团成员列表中
     */
    public void forwardSocietyMember() {
        Intent intent = new Intent(this, SocietyMemberActivity.class);
        intent.putExtra("sid", sid);
        startActivity(intent);
    }

    /**
     * 跳转到社团通知列表页面
     */
    public void forwardSocietyNotice() {
        Intent intent = new Intent(this, SocietyNoticeActivity.class);
        intent.putExtra("sid", sid);
        startActivity(intent);
    }

    /**
     * 跳转到卡片详情页面
     */
    public void forwardVideoCard(VideoCard card) {
        Intent intent = new Intent(this, VideoCardDetailActivity.class);
        intent.putExtra("cardid", card.cardid);
        startActivity(intent);
    }

    /**
     * 跳转到社团作品页面
     */
    public void forwardWorks() {
        Intent intent = new Intent(this, SocietyWorksActivity.class);
        intent.putExtra("sid", society.sid);
        startActivity(intent);
    }


    @Override
    public void initListener() {
    }


    /**
     * 提交加入社团申请
     */
    public void applyJoin() {
        if (isJoin)
            return;
        final LoadingDialog dialog = new LoadingDialog(this, "提交申请中");
        dialog.show();
        societyService.joinSociety(sid, new AbResponseListener<HashMap>(new TypeReference<Result<HashMap>>() {
        }) {
            @Override
            public void error(ServiceException e) {
                dialog.dismiss();

            }

            @Override
            public void responseInfo(Result<HashMap> data) {
                dialog.dismiss();
                mJoin.setSelected(true);
                isJoin = true;
                ToastUtil.showMessage("您的申请已经提交");
                mJoin.setText("提交审核中");
            }
        });
    }

    public void quit() {
        societyService.quit(sid, new AbResponseListener<HashMap>(new TypeReference<Result<HashMap>>() {
        }) {
            @Override
            public void error(ServiceException e) {

            }

            @Override
            public void responseInfo(Result data) {
                ToastUtil.showMessage("退出社团成功!");
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_join:

                applyJoin();
                break;
            case R.id.tv_contrubution_rank_all:
                forwardMemberRank();
                break;
            case R.id.tv_dynamic_all:
                forwardMoreDynamic();
                break;
            case R.id.ll_notifys:
            case R.id.tv_notifys:
                forwardSocietyNotice();
                //点击公告按钮
                break;
            case R.id.ll_works:
            case R.id.tv_works:
                forwardWorks();
                //点击作品按钮
                break;
            case R.id.ll_members:
            case R.id.tv_members:
                forwardSocietyMember();
                //点击成员按钮
                break;
            case R.id.ll_quit:
                quit();
                break;
            default:
                break;
        }

    }
}
